"""
Web API接口
提供HTTP接口供其他应用调用
"""

import asyncio
import json
from typing import Dict

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

from ..core.video_manager import VideoManager


app = FastAPI(title="AI视频生成API", version="0.1.0")


class VideoRequest(BaseModel):
    """视频生成请求模型"""
    text: str
    project_name: str = "AI生成视频"
    config_path: str = "config.yaml"


class VideoResponse(BaseModel):
    """视频生成响应模型"""
    success: bool
    video_path: str = ""
    draft_path: str = ""
    message: str = ""
    error: str = ""


@app.post("/generate", response_model=VideoResponse)
async def generate_video(request: VideoRequest) -> VideoResponse:
    """
    生成AI视频并导入剪映
    
    Args:
        request: 视频生成请求
        
    Returns:
        视频生成结果
    """
    try:
        manager = VideoManager(request.config_path)
        result = await manager.generate_and_import(request.text, request.project_name)
        
        return VideoResponse(**result)
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/drafts")
async def list_drafts(config_path: str = "config.yaml") -> Dict:
    """
    列出剪映草稿项目
    
    Args:
        config_path: 配置文件路径
        
    Returns:
        草稿列表
    """
    try:
        manager = VideoManager(config_path)
        drafts = manager.list_jianying_drafts()
        
        return {
            "success": True,
            "drafts": drafts,
            "count": len(drafts)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.delete("/cleanup")
async def cleanup_temp_files(config_path: str = "config.yaml") -> Dict:
    """
    清理临时文件
    
    Args:
        config_path: 配置文件路径
        
    Returns:
        清理结果
    """
    try:
        manager = VideoManager(config_path)
        manager.cleanup_temp_files()
        
        return {
            "success": True,
            "message": "临时文件清理完成"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/health")
async def health_check() -> Dict:
    """健康检查接口"""
    return {
        "status": "healthy",
        "service": "AI视频生成API",
        "version": "0.1.0"
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)